# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

# library(MetaboAnalystR)
library(gplots)
library(Hmisc)
library(dplyr)
library(tidyr)
library(tibble)

sampleInfo <- read.csv("SampleInfo.csv", header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

group <- unique(sampleInfo$ClassNote)[2]

windowsFonts(Times = windowsFont("Times New Roman"))
data <- read.csv("AllMet1.csv", header = T) %>%
    filter(! is.na(Class)) %>%
    select(- c(1, 3 : 5)) %>%
    gather("SampleID", "Value", - Name) %>%
    spread(Name, "Value") %>%
    inner_join(sampleInfo, by = c("SampleID")) %>%
    filter(ClassNote == group) %>%
    select(- c("ClassNote")) %>%
    column_to_rownames("SampleID")

head(data)

pdf("tmp.pdf", width = 8, height = 8)
# png("tmp.png", width = 1000, height = 1000)

opar <- par(no.readonly = TRUE)
par(family = "Times")


corData <- rcorr(as.matrix(data), type = "pearson")
corData <- corData$r
corData <- as.data.frame(corData) %>%
rev()
write.table(corData, "cor.txt", sep = "\t", col.names = NA, quote = FALSE)

#取消x轴y轴label
labCol = rep(NA, nrow(corData))
labRow = rep(NA, nrow(corData))

# lmat <-rbind( c(5,3,4), c(2,1,0) )
# lwid <- c(1.5, 4, 1)
# lhei <- c(1, 5)

#layout
lmat <- NULL
lwid <- NULL
lhei <- NULL

#color
colors <- rev(colorRampPalette(RColorBrewer::brewer.pal(10, "RdBu"))(256))
# colors <- colorRampPalette(c("green", "black", "red"), space = "rgb")(256)

heatmap.2(as.matrix(corData), trace = "none", density.info = "none", Colv = NULL, Rowv = NULL, labRow = labRow,
labCol = labCol, lmat = lmat, lwid = lwid, lhei = lhei, col = colors, main = paste0("pearson correlations(", group, ")"))

par(opar)

dev.off()
